home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1998 November / Freeware November 1998.img / dist / fw_elisp-manual-19.idb / usr / freeware / info / elisp-8.z / elisp-8 (.txt)
GNU Info File  |  1998-05-26  |  52KB  |  968 lines

  1. This is Info file elisp, produced by Makeinfo-1.63 from the input file
  2. elisp.texi.
  3.    This version is the edition 2.4.2 of the GNU Emacs Lisp Reference
  4. Manual.  It corresponds to Emacs Version 19.34.
  5.    Published by the Free Software Foundation 59 Temple Place, Suite 330
  6. Boston, MA  02111-1307  USA
  7.    Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1996 Free Software
  8. Foundation, Inc.
  9.    Permission is granted to make and distribute verbatim copies of this
  10. manual provided the copyright notice and this permission notice are
  11. preserved on all copies.
  12.    Permission is granted to copy and distribute modified versions of
  13. this manual under the conditions for verbatim copying, provided that the
  14. entire resulting derived work is distributed under the terms of a
  15. permission notice identical to this one.
  16.    Permission is granted to copy and distribute translations of this
  17. manual into another language, under the above conditions for modified
  18. versions, except that this permission notice may be stated in a
  19. translation approved by the Foundation.
  20.    Permission is granted to copy and distribute modified versions of
  21. this manual under the conditions for verbatim copying, provided also
  22. that the section entitled "GNU General Public License" is included
  23. exactly as in the original, and provided that the entire resulting
  24. derived work is distributed under the terms of a permission notice
  25. identical to this one.
  26.    Permission is granted to copy and distribute translations of this
  27. manual into another language, under the above conditions for modified
  28. versions, except that the section entitled "GNU General Public License"
  29. may be included in a translation approved by the Free Software
  30. Foundation instead of in the original English.
  31. File: elisp,  Node: Handling Errors,  Next: Error Symbols,  Prev: Processing of Errors,  Up: Errors
  32. Writing Code to Handle Errors
  33. .............................
  34.    The usual effect of signaling an error is to terminate the command
  35. that is running and return immediately to the Emacs editor command loop.
  36. You can arrange to trap errors occurring in a part of your program by
  37. establishing an error handler, with the special form `condition-case'.
  38. A simple example looks like this:
  39.      (condition-case nil
  40.          (delete-file filename)
  41.        (error nil))
  42. This deletes the file named FILENAME, catching any error and returning
  43. `nil' if an error occurs.
  44.    The second argument of `condition-case' is called the "protected
  45. form".  (In the example above, the protected form is a call to
  46. `delete-file'.)  The error handlers go into effect when this form
  47. begins execution and are deactivated when this form returns.  They
  48. remain in effect for all the intervening time.  In particular, they are
  49. in effect during the execution of functions called by this form, in
  50. their subroutines, and so on.  This is a good thing, since, strictly
  51. speaking, errors can be signaled only by Lisp primitives (including
  52. `signal' and `error') called by the protected form, not by the
  53. protected form itself.
  54.    The arguments after the protected form are handlers.  Each handler
  55. lists one or more "condition names" (which are symbols) to specify
  56. which errors it will handle.  The error symbol specified when an error
  57. is signaled also defines a list of condition names.  A handler applies
  58. to an error if they have any condition names in common.  In the example
  59. above, there is one handler, and it specifies one condition name,
  60. `error', which covers all errors.
  61.    The search for an applicable handler checks all the established
  62. handlers starting with the most recently established one.  Thus, if two
  63. nested `condition-case' forms offer to handle the same error, the inner
  64. of the two will actually handle it.
  65.    When an error is handled, control returns to the handler.  Before
  66. this happens, Emacs unbinds all variable bindings made by binding
  67. constructs that are being exited and executes the cleanups of all
  68. `unwind-protect' forms that are exited.  Once control arrives at the
  69. handler, the body of the handler is executed.
  70.    After execution of the handler body, execution returns from the
  71. `condition-case' form.  Because the protected form is exited completely
  72. before execution of the handler, the handler cannot resume execution at
  73. the point of the error, nor can it examine variable bindings that were
  74. made within the protected form.  All it can do is clean up and proceed.
  75.    `condition-case' is often used to trap errors that are predictable,
  76. such as failure to open a file in a call to `insert-file-contents'.  It
  77. is also used to trap errors that are totally unpredictable, such as
  78. when the program evaluates an expression read from the user.
  79.    Error signaling and handling have some resemblance to `throw' and
  80. `catch', but they are entirely separate facilities.  An error cannot be
  81. caught by a `catch', and a `throw' cannot be handled by an error
  82. handler (though using `throw' when there is no suitable `catch' signals
  83. an error that can be handled).
  84.  - Special Form: condition-case VAR PROTECTED-FORM HANDLERS...
  85.      This special form establishes the error handlers HANDLERS around
  86.      the execution of PROTECTED-FORM.  If PROTECTED-FORM executes
  87.      without error, the value it returns becomes the value of the
  88.      `condition-case' form; in this case, the `condition-case' has no
  89.      effect.  The `condition-case' form makes a difference when an
  90.      error occurs during PROTECTED-FORM.
  91.      Each of the HANDLERS is a list of the form `(CONDITIONS BODY...)'.
  92.      Here CONDITIONS is an error condition name to be handled, or a
  93.      list of condition names; BODY is one or more Lisp expressions to
  94.      be executed when this handler handles an error.  Here are examples
  95.      of handlers:
  96.           (error nil)
  97.           
  98.           (arith-error (message "Division by zero"))
  99.           
  100.           ((arith-error file-error)
  101.            (message
  102.             "Either division by zero or failure to open a file"))
  103.      Each error that occurs has an "error symbol" that describes what
  104.      kind of error it is.  The `error-conditions' property of this
  105.      symbol is a list of condition names (*note Error Symbols::.).
  106.      Emacs searches all the active `condition-case' forms for a handler
  107.      that specifies one or more of these condition names; the innermost
  108.      matching `condition-case' handles the error.  Within this
  109.      `condition-case', the first applicable handler handles the error.
  110.      After executing the body of the handler, the `condition-case'
  111.      returns normally, using the value of the last form in the handler
  112.      body as the overall value.
  113.      The argument VAR is a variable.  `condition-case' does not bind
  114.      this variable when executing the PROTECTED-FORM, only when it
  115.      handles an error.  At that time, it binds VAR locally to an "error
  116.      description", which is a list giving the particulars of the error.
  117.      The error description has the form `(ERROR-SYMBOL . DATA)'.  The
  118.      handler can refer to this list to decide what to do.  For example,
  119.      if the error is for failure opening a file, the file name is the
  120.      second element of DATA--the third element of the error description.
  121.      If VAR is `nil', that means no variable is bound.  Then the error
  122.      symbol and associated data are not available to the handler.
  123.  - Function: error-message-string ERROR-DESCRIPTION
  124.      This function returns the error message string for a given error
  125.      descriptor.  It is useful if you want to handle an error by
  126.      printing the usual error message for that error.
  127.    Here is an example of using `condition-case' to handle the error
  128. that results from dividing by zero.  The handler displays the error
  129. message (but without a beep), then returns a very large number.
  130.      (defun safe-divide (dividend divisor)
  131.        (condition-case err
  132.            ;; Protected form.
  133.            (/ dividend divisor)
  134.          ;; The handler.
  135.          (arith-error                        ; Condition.
  136.           ;; Display the usual message for this error.
  137.           (message "%s" (error-message-string err))
  138.           1000000)))
  139.      => safe-divide
  140.      (safe-divide 5 0)
  141.           -| Arithmetic error: (arith-error)
  142.      => 1000000
  143. The handler specifies condition name `arith-error' so that it will
  144. handle only division-by-zero errors.  Other kinds of errors will not be
  145. handled, at least not by this `condition-case'.  Thus,
  146.      (safe-divide nil 3)
  147.           error--> Wrong type argument: integer-or-marker-p, nil
  148.    Here is a `condition-case' that catches all kinds of errors,
  149. including those signaled with `error':
  150.      (setq baz 34)
  151.           => 34
  152.      (condition-case err
  153.          (if (eq baz 35)
  154.              t
  155.            ;; This is a call to the function `error'.
  156.            (error "Rats!  The variable %s was %s, not 35" 'baz baz))
  157.        ;; This is the handler; it is not a form.
  158.        (error (princ (format "The error was: %s" err))
  159.               2))
  160.      -| The error was: (error "Rats!  The variable baz was 34, not 35")
  161.      => 2
  162. File: elisp,  Node: Error Symbols,  Prev: Handling Errors,  Up: Errors
  163. Error Symbols and Condition Names
  164. .................................
  165.    When you signal an error, you specify an "error symbol" to specify
  166. the kind of error you have in mind.  Each error has one and only one
  167. error symbol to categorize it.  This is the finest classification of
  168. errors defined by the Emacs Lisp language.
  169.    These narrow classifications are grouped into a hierarchy of wider
  170. classes called "error conditions", identified by "condition names".
  171. The narrowest such classes belong to the error symbols themselves: each
  172. error symbol is also a condition name.  There are also condition names
  173. for more extensive classes, up to the condition name `error' which
  174. takes in all kinds of errors.  Thus, each error has one or more
  175. condition names: `error', the error symbol if that is distinct from
  176. `error', and perhaps some intermediate classifications.
  177.    In order for a symbol to be an error symbol, it must have an
  178. `error-conditions' property which gives a list of condition names.
  179. This list defines the conditions that this kind of error belongs to.
  180. (The error symbol itself, and the symbol `error', should always be
  181. members of this list.)  Thus, the hierarchy of condition names is
  182. defined by the `error-conditions' properties of the error symbols.
  183.    In addition to the `error-conditions' list, the error symbol should
  184. have an `error-message' property whose value is a string to be printed
  185. when that error is signaled but not handled.  If the `error-message'
  186. property exists, but is not a string, the error message `peculiar
  187. error' is used.
  188.    Here is how we define a new error symbol, `new-error':
  189.      (put 'new-error
  190.           'error-conditions
  191.           '(error my-own-errors new-error))
  192.      => (error my-own-errors new-error)
  193.      (put 'new-error 'error-message "A new error")
  194.      => "A new error"
  195. This error has three condition names: `new-error', the narrowest
  196. classification; `my-own-errors', which we imagine is a wider
  197. classification; and `error', which is the widest of all.
  198.    The error string should start with a capital letter but it should
  199. not end with a period.  This is for consistency with the rest of Emacs.
  200.    Naturally, Emacs will never signal `new-error' on its own; only an
  201. explicit call to `signal' (*note Signaling Errors::.) in your code can
  202. do this:
  203.      (signal 'new-error '(x y))
  204.           error--> A new error: x, y
  205.    This error can be handled through any of the three condition names.
  206. This example handles `new-error' and any other errors in the class
  207. `my-own-errors':
  208.      (condition-case foo
  209.          (bar nil t)
  210.        (my-own-errors nil))
  211.    The significant way that errors are classified is by their condition
  212. names--the names used to match errors with handlers.  An error symbol
  213. serves only as a convenient way to specify the intended error message
  214. and list of condition names.  It would be cumbersome to give `signal' a
  215. list of condition names rather than one error symbol.
  216.    By contrast, using only error symbols without condition names would
  217. seriously decrease the power of `condition-case'.  Condition names make
  218. it possible to categorize errors at various levels of generality when
  219. you write an error handler.  Using error symbols alone would eliminate
  220. all but the narrowest level of classification.
  221.    *Note Standard Errors::, for a list of all the standard error symbols
  222. and their conditions.
  223. File: elisp,  Node: Cleanups,  Prev: Errors,  Up: Nonlocal Exits
  224. Cleaning Up from Nonlocal Exits
  225. -------------------------------
  226.    The `unwind-protect' construct is essential whenever you temporarily
  227. put a data structure in an inconsistent state; it permits you to ensure
  228. the data are consistent in the event of an error or throw.
  229.  - Special Form: unwind-protect BODY CLEANUP-FORMS...
  230.      `unwind-protect' executes the BODY with a guarantee that the
  231.      CLEANUP-FORMS will be evaluated if control leaves BODY, no matter
  232.      how that happens.  The BODY may complete normally, or execute a
  233.      `throw' out of the `unwind-protect', or cause an error; in all
  234.      cases, the CLEANUP-FORMS will be evaluated.
  235.      If the BODY forms finish normally, `unwind-protect' returns the
  236.      value of the last BODY form, after it evaluates the CLEANUP-FORMS.
  237.      If the BODY forms do not finish, `unwind-protect' does not return
  238.      any value in the normal sense.
  239.      Only the BODY is actually protected by the `unwind-protect'.  If
  240.      any of the CLEANUP-FORMS themselves exits nonlocally (e.g., via a
  241.      `throw' or an error), `unwind-protect' is *not* guaranteed to
  242.      evaluate the rest of them.  If the failure of one of the
  243.      CLEANUP-FORMS has the potential to cause trouble, then protect it
  244.      with another `unwind-protect' around that form.
  245.      The number of currently active `unwind-protect' forms counts,
  246.      together with the number of local variable bindings, against the
  247.      limit `max-specpdl-size' (*note Local Variables::.).
  248.    For example, here we make an invisible buffer for temporary use, and
  249. make sure to kill it before finishing:
  250.      (save-excursion
  251.        (let ((buffer (get-buffer-create " *temp*")))
  252.          (set-buffer buffer)
  253.          (unwind-protect
  254.              BODY
  255.            (kill-buffer buffer))))
  256. You might think that we could just as well write `(kill-buffer
  257. (current-buffer))' and dispense with the variable `buffer'.  However,
  258. the way shown above is safer, if BODY happens to get an error after
  259. switching to a different buffer!  (Alternatively, you could write
  260. another `save-excursion' around the body, to ensure that the temporary
  261. buffer becomes current in time to kill it.)
  262.    Here is an actual example taken from the file `ftp.el'.  It creates
  263. a process (*note Processes::.) to try to establish a connection to a
  264. remote machine.  As the function `ftp-login' is highly susceptible to
  265. numerous problems that the writer of the function cannot anticipate, it
  266. is protected with a form that guarantees deletion of the process in the
  267. event of failure.  Otherwise, Emacs might fill up with useless
  268. subprocesses.
  269.      (let ((win nil))
  270.        (unwind-protect
  271.            (progn
  272.              (setq process (ftp-setup-buffer host file))
  273.              (if (setq win (ftp-login process host user password))
  274.                  (message "Logged in")
  275.                (error "Ftp login failed")))
  276.          (or win (and process (delete-process process)))))
  277.    This example actually has a small bug: if the user types `C-g' to
  278. quit, and the quit happens immediately after the function
  279. `ftp-setup-buffer' returns but before the variable `process' is set,
  280. the process will not be killed.  There is no easy way to fix this bug,
  281. but at least it is very unlikely.
  282.    Here is another example which uses `unwind-protect' to make sure to
  283. kill a temporary buffer.  In this example, the value returned by
  284. `unwind-protect' is used.
  285.      (defun shell-command-string (cmd)
  286.        "Return the output of the shell command CMD, as a string."
  287.        (save-excursion
  288.          (set-buffer (generate-new-buffer " OS*cmd"))
  289.          (shell-command cmd t)
  290.          (unwind-protect
  291.              (buffer-string)
  292.            (kill-buffer (current-buffer)))))
  293. File: elisp,  Node: Variables,  Next: Functions,  Prev: Control Structures,  Up: Top
  294. Variables
  295. *********
  296.    A "variable" is a name used in a program to stand for a value.
  297. Nearly all programming languages have variables of some sort.  In the
  298. text of a Lisp program, variables are written using the syntax for
  299. symbols.
  300.    In Lisp, unlike most programming languages, programs are represented
  301. primarily as Lisp objects and only secondarily as text.  The Lisp
  302. objects used for variables are symbols: the symbol name is the variable
  303. name, and the variable's value is stored in the value cell of the
  304. symbol.  The use of a symbol as a variable is independent of its use as
  305. a function name.  *Note Symbol Components::.
  306.    The Lisp objects that constitute a Lisp program determine the textual
  307. form of the program--it is simply the read syntax for those Lisp
  308. objects.  This is why, for example, a variable in a textual Lisp program
  309. is written using the read syntax for the symbol that represents the
  310. variable.
  311. * Menu:
  312. * Global Variables::      Variable values that exist permanently, everywhere.
  313. * Constant Variables::    Certain "variables" have values that never change.
  314. * Local Variables::       Variable values that exist only temporarily.
  315. * Void Variables::        Symbols that lack values.
  316. * Defining Variables::    A definition says a symbol is used as a variable.
  317. * Tips for Defining::     How to avoid bad results from quitting
  318.                             within the code to initialize a variable.
  319. * Accessing Variables::   Examining values of variables whose names
  320.                             are known only at run time.
  321. * Setting Variables::     Storing new values in variables.
  322. * Variable Scoping::      How Lisp chooses among local and global values.
  323. * Buffer-Local Variables::  Variable values in effect only in one buffer.
  324. File: elisp,  Node: Global Variables,  Next: Constant Variables,  Up: Variables
  325. Global Variables
  326. ================
  327.    The simplest way to use a variable is "globally".  This means that
  328. the variable has just one value at a time, and this value is in effect
  329. (at least for the moment) throughout the Lisp system.  The value remains
  330. in effect until you specify a new one.  When a new value replaces the
  331. old one, no trace of the old value remains in the variable.
  332.    You specify a value for a symbol with `setq'.  For example,
  333.      (setq x '(a b))
  334. gives the variable `x' the value `(a b)'.  Note that `setq' does not
  335. evaluate its first argument, the name of the variable, but it does
  336. evaluate the second argument, the new value.
  337.    Once the variable has a value, you can refer to it by using the
  338. symbol by itself as an expression.  Thus,
  339.      x => (a b)
  340. assuming the `setq' form shown above has already been executed.
  341.    If you do another `setq', the new value replaces the old one:
  342.      x
  343.           => (a b)
  344.      (setq x 4)
  345.           => 4
  346.      x
  347.           => 4
  348. File: elisp,  Node: Constant Variables,  Next: Local Variables,  Prev: Global Variables,  Up: Variables
  349. Variables That Never Change
  350. ===========================
  351.    Emacs Lisp has two special symbols, `nil' and `t', that always
  352. evaluate to themselves.  These symbols cannot be rebound, nor can their
  353. value cells be changed.  An attempt to change the value of `nil' or `t'
  354. signals a `setting-constant' error.
  355.      nil == 'nil
  356.           => nil
  357.      (setq nil 500)
  358.      error--> Attempt to set constant symbol: nil
  359. File: elisp,  Node: Local Variables,  Next: Void Variables,  Prev: Constant Variables,  Up: Variables
  360. Local Variables
  361. ===============
  362.    Global variables have values that last until explicitly superseded
  363. with new values.  Sometimes it is useful to create variable values that
  364. exist temporarily--only while within a certain part of the program.
  365. These values are called "local", and the variables so used are called
  366. "local variables".
  367.    For example, when a function is called, its argument variables
  368. receive new local values that last until the function exits.  The `let'
  369. special form explicitly establishes new local values for specified
  370. variables; these last until exit from the `let' form.
  371.    Establishing a local value saves away the previous value (or lack of
  372. one) of the variable.  When the life span of the local value is over,
  373. the previous value is restored.  In the mean time, we say that the
  374. previous value is "shadowed" and "not visible".  Both global and local
  375. values may be shadowed (*note Scope::.).
  376.    If you set a variable (such as with `setq') while it is local, this
  377. replaces the local value; it does not alter the global value, or
  378. previous local values that are shadowed.  To model this behavior, we
  379. speak of a "local binding" of the variable as well as a local value.
  380.    The local binding is a conceptual place that holds a local value.
  381. Entry to a function, or a special form such as `let', creates the local
  382. binding; exit from the function or from the `let' removes the local
  383. binding.  As long as the local binding lasts, the variable's value is
  384. stored within it.  Use of `setq' or `set' while there is a local
  385. binding stores a different value into the local binding; it does not
  386. create a new binding.
  387.    We also speak of the "global binding", which is where (conceptually)
  388. the global value is kept.
  389.    A variable can have more than one local binding at a time (for
  390. example, if there are nested `let' forms that bind it).  In such a
  391. case, the most recently created local binding that still exists is the
  392. "current binding" of the variable.  (This is called "dynamic scoping";
  393. see *Note Variable Scoping::.)  If there are no local bindings, the
  394. variable's global binding is its current binding.  We also call the
  395. current binding the "most-local existing binding", for emphasis.
  396. Ordinary evaluation of a symbol always returns the value of its current
  397. binding.
  398.    The special forms `let' and `let*' exist to create local bindings.
  399.  - Special Form: let (BINDINGS...) FORMS...
  400.      This special form binds variables according to BINDINGS and then
  401.      evaluates all of the FORMS in textual order.  The `let'-form
  402.      returns the value of the last form in FORMS.
  403.      Each of the BINDINGS is either (i) a symbol, in which case that
  404.      symbol is bound to `nil'; or (ii) a list of the form `(SYMBOL
  405.      VALUE-FORM)', in which case SYMBOL is bound to the result of
  406.      evaluating VALUE-FORM.  If VALUE-FORM is omitted, `nil' is used.
  407.      All of the VALUE-FORMs in BINDINGS are evaluated in the order they
  408.      appear and *before* any of the symbols are bound.  Here is an
  409.      example of this: `Z' is bound to the old value of `Y', which is 2,
  410.      not the new value, 1.
  411.           (setq Y 2)
  412.                => 2
  413.           (let ((Y 1)
  414.                 (Z Y))
  415.             (list Y Z))
  416.                => (1 2)
  417.  - Special Form: let* (BINDINGS...) FORMS...
  418.      This special form is like `let', but it binds each variable right
  419.      after computing its local value, before computing the local value
  420.      for the next variable.  Therefore, an expression in BINDINGS can
  421.      reasonably refer to the preceding symbols bound in this `let*'
  422.      form.  Compare the following example with the example above for
  423.      `let'.
  424.           (setq Y 2)
  425.                => 2
  426.           (let* ((Y 1)
  427.                  (Z Y))    ; Use the just-established value of `Y'.
  428.             (list Y Z))
  429.                => (1 1)
  430.    Here is a complete list of the other facilities that create local
  431. bindings:
  432.    * Function calls (*note Functions::.).
  433.    * Macro calls (*note Macros::.).
  434.    * `condition-case' (*note Errors::.).
  435.    Variables can also have buffer-local bindings (*note Buffer-Local
  436. Variables::.); a few variables have terminal-local bindings (*note
  437. Multiple Displays::.).  These kinds of bindings work somewhat like
  438. ordinary local bindings, but they are localized depending on "where"
  439. you are in Emacs, rather than localized in time.
  440.  - Variable: max-specpdl-size
  441.      This variable defines the limit on the total number of local
  442.      variable bindings and `unwind-protect' cleanups (*note Nonlocal
  443.      Exits::.) that are allowed before signaling an error (with data
  444.      `"Variable binding depth exceeds max-specpdl-size"').
  445.      This limit, with the associated error when it is exceeded, is one
  446.      way that Lisp avoids infinite recursion on an ill-defined function.
  447.      The default value is 600.
  448.      `max-lisp-eval-depth' provides another limit on depth of nesting.
  449.      *Note Eval::.
  450. File: elisp,  Node: Void Variables,  Next: Defining Variables,  Prev: Local Variables,  Up: Variables
  451. When a Variable is "Void"
  452. =========================
  453.    If you have never given a symbol any value as a global variable, we
  454. say that that symbol's global value is "void".  In other words, the
  455. symbol's value cell does not have any Lisp object in it.  If you try to
  456. evaluate the symbol, you get a `void-variable' error rather than a
  457. value.
  458.    Note that a value of `nil' is not the same as void.  The symbol
  459. `nil' is a Lisp object and can be the value of a variable just as any
  460. other object can be; but it is *a value*.  A void variable does not
  461. have any value.
  462.    After you have given a variable a value, you can make it void once
  463. more using `makunbound'.
  464.  - Function: makunbound SYMBOL
  465.      This function makes the current binding of SYMBOL void.
  466.      Subsequent attempts to use this symbol's value as a variable will
  467.      signal the error `void-variable', unless or until you set it again.
  468.      `makunbound' returns SYMBOL.
  469.           (makunbound 'x)      ; Make the global value
  470.                                ;   of `x' void.
  471.                => x
  472.           x
  473.           error--> Symbol's value as variable is void: x
  474.      If SYMBOL is locally bound, `makunbound' affects the most local
  475.      existing binding.  This is the only way a symbol can have a void
  476.      local binding, since all the constructs that create local bindings
  477.      create them with values.  In this case, the voidness lasts at most
  478.      as long as the binding does; when the binding is removed due to
  479.      exit from the construct that made it, the previous or global
  480.      binding is reexposed as usual, and the variable is no longer void
  481.      unless the newly reexposed binding was void all along.
  482.           (setq x 1)               ; Put a value in the global binding.
  483.                => 1
  484.           (let ((x 2))             ; Locally bind it.
  485.             (makunbound 'x)        ; Void the local binding.
  486.             x)
  487.           error--> Symbol's value as variable is void: x
  488.           x                        ; The global binding is unchanged.
  489.                => 1
  490.           
  491.           (let ((x 2))             ; Locally bind it.
  492.             (let ((x 3))           ; And again.
  493.               (makunbound 'x)      ; Void the innermost-local binding.
  494.               x))                  ; And refer: it's void.
  495.           error--> Symbol's value as variable is void: x
  496.           (let ((x 2))
  497.             (let ((x 3))
  498.               (makunbound 'x))     ; Void inner binding, then remove it.
  499.             x)                     ; Now outer `let' binding is visible.
  500.                => 2
  501.    A variable that has been made void with `makunbound' is
  502. indistinguishable from one that has never received a value and has
  503. always been void.
  504.    You can use the function `boundp' to test whether a variable is
  505. currently void.
  506.  - Function: boundp VARIABLE
  507.      `boundp' returns `t' if VARIABLE (a symbol) is not void; more
  508.      precisely, if its current binding is not void.  It returns `nil'
  509.      otherwise.
  510.           (boundp 'abracadabra)          ; Starts out void.
  511.                => nil
  512.           (let ((abracadabra 5))         ; Locally bind it.
  513.             (boundp 'abracadabra))
  514.                => t
  515.           (boundp 'abracadabra)          ; Still globally void.
  516.                => nil
  517.           (setq abracadabra 5)           ; Make it globally nonvoid.
  518.                => 5
  519.           (boundp 'abracadabra)
  520.                => t
  521. File: elisp,  Node: Defining Variables,  Next: Tips for Defining,  Prev: Void Variables,  Up: Variables
  522. Defining Global Variables
  523. =========================
  524.    You may announce your intention to use a symbol as a global variable
  525. with a "variable definition": a special form, either `defconst' or
  526. `defvar'.
  527.    In Emacs Lisp, definitions serve three purposes.  First, they inform
  528. people who read the code that certain symbols are *intended* to be used
  529. a certain way (as variables).  Second, they inform the Lisp system of
  530. these things, supplying a value and documentation.  Third, they provide
  531. information to utilities such as `etags' and `make-docfile', which
  532. create data bases of the functions and variables in a program.
  533.    The difference between `defconst' and `defvar' is primarily a matter
  534. of intent, serving to inform human readers of whether programs will
  535. change the variable.  Emacs Lisp does not restrict the ways in which a
  536. variable can be used based on `defconst' or `defvar' declarations.
  537. However, it does make a difference for initialization: `defconst'
  538. unconditionally initializes the variable, while `defvar' initializes it
  539. only if it is void.
  540.    One would expect user option variables to be defined with
  541. `defconst', since programs do not change them.  Unfortunately, this has
  542. bad results if the definition is in a library that is not preloaded:
  543. `defconst' would override any prior value when the library is loaded.
  544. Users would like to be able to set user options in their init files,
  545. and override the default values given in the definitions.  For this
  546. reason, user options must be defined with `defvar'.
  547.  - Special Form: defvar SYMBOL [VALUE [DOC-STRING]]
  548.      This special form defines SYMBOL as a value and initializes it.
  549.      The definition informs a person reading your code that SYMBOL is
  550.      used as a variable that programs are likely to set or change.  It
  551.      is also used for all user option variables except in the preloaded
  552.      parts of Emacs.  Note that SYMBOL is not evaluated; the symbol to
  553.      be defined must appear explicitly in the `defvar'.
  554.      If SYMBOL already has a value (i.e., it is not void), VALUE is not
  555.      even evaluated, and SYMBOL's value remains unchanged.  If SYMBOL
  556.      is void and VALUE is specified, `defvar' evaluates it and sets
  557.      SYMBOL to the result.  (If VALUE is omitted, the value of SYMBOL
  558.      is not changed in any case.)
  559.      When you evaluate a top-level `defvar' form with `C-M-x' in Emacs
  560.      Lisp mode (`eval-defun'), a special feature of `eval-defun'
  561.      evaluates it as a `defconst'.  The purpose of this is to make sure
  562.      the variable's value is reinitialized, when you ask for it
  563.      specifically.
  564.      If SYMBOL has a buffer-local binding in the current buffer,
  565.      `defvar' sets the default value, not the local value.  *Note
  566.      Buffer-Local Variables::.
  567.      If the DOC-STRING argument appears, it specifies the documentation
  568.      for the variable.  (This opportunity to specify documentation is
  569.      one of the main benefits of defining the variable.)  The
  570.      documentation is stored in the symbol's `variable-documentation'
  571.      property.  The Emacs help functions (*note Documentation::.) look
  572.      for this property.
  573.      If the first character of DOC-STRING is `*', it means that this
  574.      variable is considered a user option.  This lets users set the
  575.      variable conventiently using the commands `set-variable' and
  576.      `edit-options'.
  577.      For example, this form defines `foo' but does not set its value:
  578.           (defvar foo)
  579.                => foo
  580.      The following example sets the value of `bar' to `23', and gives
  581.      it a documentation string:
  582.           (defvar bar 23
  583.             "The normal weight of a bar.")
  584.                => bar
  585.      The following form changes the documentation string for `bar',
  586.      making it a user option, but does not change the value, since `bar'
  587.      already has a value.  (The addition `(1+ 23)' is not even
  588.      performed.)
  589.           (defvar bar (1+ 23)
  590.             "*The normal weight of a bar.")
  591.                => bar
  592.           bar
  593.                => 23
  594.      Here is an equivalent expression for the `defvar' special form:
  595.           (defvar SYMBOL VALUE DOC-STRING)
  596.           ==
  597.           (progn
  598.             (if (not (boundp 'SYMBOL))
  599.                 (setq SYMBOL VALUE))
  600.             (if 'DOC-STRING
  601.               (put 'SYMBOL 'variable-documentation 'DOC-STRING))
  602.             'SYMBOL)
  603.      The `defvar' form returns SYMBOL, but it is normally used at top
  604.      level in a file where its value does not matter.
  605.  - Special Form: defconst SYMBOL [VALUE [DOC-STRING]]
  606.      This special form defines SYMBOL as a value and initializes it.
  607.      It informs a person reading your code that SYMBOL has a global
  608.      value, established here, that will not normally be changed or
  609.      locally bound by the execution of the program.  The user, however,
  610.      may be welcome to change it.  Note that SYMBOL is not evaluated;
  611.      the symbol to be defined must appear explicitly in the `defconst'.
  612.      `defconst' always evaluates VALUE and sets the global value of
  613.      SYMBOL to the result, provided VALUE is given.  If SYMBOL has a
  614.      buffer-local binding in the current buffer, `defconst' sets the
  615.      default value, not the local value.
  616.      *Please note:* Don't use `defconst' for user option variables in
  617.      libraries that are not standardly preloaded.  The user should be
  618.      able to specify a value for such a variable in the `.emacs' file,
  619.      so that it will be in effect if and when the library is loaded
  620.      later.
  621.      Here, `pi' is a constant that presumably ought not to be changed
  622.      by anyone (attempts by the Indiana State Legislature
  623.      notwithstanding).  As the second form illustrates, however, this
  624.      is only advisory.
  625.           (defconst pi 3.1415 "Pi to five places.")
  626.                => pi
  627.           (setq pi 3)
  628.                => pi
  629.           pi
  630.                => 3
  631.  - Function: user-variable-p VARIABLE
  632.      This function returns `t' if VARIABLE is a user option--a variable
  633.      intended to be set by the user for customization--and `nil'
  634.      otherwise.  (Variables other than user options exist for the
  635.      internal purposes of Lisp programs, and users need not know about
  636.      them.)
  637.      User option variables are distinguished from other variables by the
  638.      first character of the `variable-documentation' property.  If the
  639.      property exists and is a string, and its first character is `*',
  640.      then the variable is a user option.
  641.    If a user option variable has a `variable-interactive' property, the
  642. `set-variable' command uses that value to control reading the new value
  643. for the variable.  The property's value is used as if it were to
  644. `interactive' (*note Using Interactive::.).
  645.    *Warning:* If the `defconst' and `defvar' special forms are used
  646. while the variable has a local binding, they set the local binding's
  647. value; the global binding is not changed.  This is not what we really
  648. want.  To prevent it, use these special forms at top level in a file,
  649. where normally no local binding is in effect, and make sure to load the
  650. file before making a local binding for the variable.
  651. File: elisp,  Node: Tips for Defining,  Next: Accessing Variables,  Prev: Defining Variables,  Up: Variables
  652. Tips for Defining Variables Robustly
  653. ====================================
  654.    When defining and initializing a variable that holds a complicated
  655. value (such as a keymap with bindings in it), it's best to put the
  656. entire computation of the value into the `defvar', like this:
  657.      (defvar my-mode-map
  658.        (let ((map (make-sparse-keymap)))
  659.          (define-key my-mode-map "\C-c\C-a" 'my-command)
  660.          ...
  661.          map)
  662.        DOCSTRING)
  663. This method has several benefits.  First, if the user quits while
  664. loading the file, the variable is either still uninitialized or
  665. initialized properly, never in-between.  If it is uninitialized,
  666. reloading the file will initialize it properly.  Second, reloading the
  667. file once the variable is initialized will not alter it; that is
  668. important if the user has run hooks to alter part of the contents (such
  669. as, to rebind keys).  Third, evaluating the `defvar' form with `C-M-x'
  670. *will* reinitialize the map completely.
  671.    Putting so much code in the `defvar' form has one disadvantage: it
  672. puts the documentation string far away from the line which names the
  673. variable.  Here's a safe way to avoid that:
  674.      (defvar my-mode-map nil
  675.        DOCSTRING)
  676.      (if my-mode-map
  677.          nil
  678.        (let ((map (make-sparse-keymap)))
  679.          (define-key my-mode-map "\C-c\C-a" 'my-command)
  680.          ...
  681.          (setq my-mode-map map)))
  682. This has all the same advantages as putting the initialization inside
  683. the `defvar', except that you must type `C-M-x' twice, once on each
  684. form, if you do want to reinitialize the variable.
  685.    But be careful not to write the code like this:
  686.      (defvar my-mode-map nil
  687.        DOCSTRING)
  688.      (if my-mode-map
  689.          nil
  690.        (setq my-mode-map (make-sparse-keymap))
  691.        (define-key my-mode-map "\C-c\C-a" 'my-command)
  692.        ...)
  693. This code sets the variable, then alters it, but only if the variable
  694. had been `ni'.  If the user quits just after the `setq', that leaves
  695. the variable neither correctly initialized nor void nor `nil'.  Once
  696. that happens, reloading the file will not initialize the variable; it
  697. will remain incomplete.
  698. File: elisp,  Node: Accessing Variables,  Next: Setting Variables,  Prev: Tips for Defining,  Up: Variables
  699. Accessing Variable Values
  700. =========================
  701.    The usual way to reference a variable is to write the symbol which
  702. names it (*note Symbol Forms::.).  This requires you to specify the
  703. variable name when you write the program.  Usually that is exactly what
  704. you want to do.  Occasionally you need to choose at run time which
  705. variable to reference; then you can use `symbol-value'.
  706.  - Function: symbol-value SYMBOL
  707.      This function returns the value of SYMBOL.  This is the value in
  708.      the innermost local binding of the symbol, or its global value if
  709.      it has no local bindings.
  710.           (setq abracadabra 5)
  711.                => 5
  712.           (setq foo 9)
  713.                => 9
  714.           
  715.           ;; Here the symbol `abracadabra'
  716.           ;;   is the symbol whose value is examined.
  717.           (let ((abracadabra 'foo))
  718.             (symbol-value 'abracadabra))
  719.                => foo
  720.           
  721.           ;; Here the value of `abracadabra',
  722.           ;;   which is `foo',
  723.           ;;   is the symbol whose value is examined.
  724.           (let ((abracadabra 'foo))
  725.             (symbol-value abracadabra))
  726.                => 9
  727.           
  728.           (symbol-value 'abracadabra)
  729.                => 5
  730.      A `void-variable' error is signaled if SYMBOL has neither a local
  731.      binding nor a global value.
  732. File: elisp,  Node: Setting Variables,  Next: Variable Scoping,  Prev: Accessing Variables,  Up: Variables
  733. How to Alter a Variable Value
  734. =============================
  735.    The usual way to change the value of a variable is with the special
  736. form `setq'.  When you need to compute the choice of variable at run
  737. time, use the function `set'.
  738.  - Special Form: setq [SYMBOL FORM]...
  739.      This special form is the most common method of changing a
  740.      variable's value.  Each SYMBOL is given a new value, which is the
  741.      result of evaluating the corresponding FORM.  The most-local
  742.      existing binding of the symbol is changed.
  743.      `setq' does not evaluate SYMBOL; it sets the symbol that you
  744.      write.  We say that this argument is "automatically quoted".  The
  745.      `q' in `setq' stands for "quoted."
  746.      The value of the `setq' form is the value of the last FORM.
  747.           (setq x (1+ 2))
  748.                => 3
  749.           x                   ; `x' now has a global value.
  750.                => 3
  751.           (let ((x 5))
  752.             (setq x 6)        ; The local binding of `x' is set.
  753.             x)
  754.                => 6
  755.           x                   ; The global value is unchanged.
  756.                => 3
  757.      Note that the first FORM is evaluated, then the first SYMBOL is
  758.      set, then the second FORM is evaluated, then the second SYMBOL is
  759.      set, and so on:
  760.           (setq x 10          ; Notice that `x' is set before
  761.                 y (1+ x))     ;   the value of `y' is computed.
  762.                => 11
  763.  - Function: set SYMBOL VALUE
  764.      This function sets SYMBOL's value to VALUE, then returns VALUE.
  765.      Since `set' is a function, the expression written for SYMBOL is
  766.      evaluated to obtain the symbol to set.
  767.      The most-local existing binding of the variable is the binding
  768.      that is set; shadowed bindings are not affected.
  769.           (set one 1)
  770.           error--> Symbol's value as variable is void: one
  771.           (set 'one 1)
  772.                => 1
  773.           (set 'two 'one)
  774.                => one
  775.           (set two 2)         ; `two' evaluates to symbol `one'.
  776.                => 2
  777.           one                 ; So it is `one' that was set.
  778.                => 2
  779.           (let ((one 1))      ; This binding of `one' is set,
  780.             (set 'one 3)      ;   not the global value.
  781.             one)
  782.                => 3
  783.           one
  784.                => 2
  785.      If SYMBOL is not actually a symbol, a `wrong-type-argument' error
  786.      is signaled.
  787.           (set '(x y) 'z)
  788.           error--> Wrong type argument: symbolp, (x y)
  789.      Logically speaking, `set' is a more fundamental primitive than
  790.      `setq'.  Any use of `setq' can be trivially rewritten to use
  791.      `set'; `setq' could even be defined as a macro, given the
  792.      availability of `set'.  However, `set' itself is rarely used;
  793.      beginners hardly need to know about it.  It is useful only for
  794.      choosing at run time which variable to set.  For example, the
  795.      command `set-variable', which reads a variable name from the user
  796.      and then sets the variable, needs to use `set'.
  797.           Common Lisp note: In Common Lisp, `set' always changes the
  798.           symbol's special value, ignoring any lexical bindings.  In
  799.           Emacs Lisp, all variables and all bindings are (in effect)
  800.           special, so `set' always affects the most local existing
  801.           binding.
  802.    One other function for setting a variable is designed to add an
  803. element to a list if it is not already present in the list.
  804.  - Function: add-to-list SYMBOL ELEMENT
  805.      This function sets the variable SYMBOL by consing ELEMENT onto the
  806.      old value, if ELEMENT is not already a member of that value.  It
  807.      returns the resulting list, whether updated or not.  The value of
  808.      SYMBOL had better be a list already before the call.
  809.      The argument SYMBOL is not implicitly quoted; `add-to-list' is an
  810.      ordinary function, like `set' and unlike `setq'.  Quote the
  811.      argument yourself if that is what you want.
  812.      Here's a scenario showing how to use `add-to-list':
  813.           (setq foo '(a b))
  814.                => (a b)
  815.           
  816.           (add-to-list 'foo 'c)     ;; Add `c'.
  817.                => (c a b)
  818.           
  819.           (add-to-list 'foo 'b)     ;; No effect.
  820.                => (c a b)
  821.           
  822.           foo                       ;; `foo' was changed.
  823.                => (c a b)
  824.    An equivalent expression for `(add-to-list 'VAR VALUE)' is this:
  825.      (or (member VALUE VAR)
  826.          (setq VAR (cons VALUE VAR)))
  827. File: elisp,  Node: Variable Scoping,  Next: Buffer-Local Variables,  Prev: Setting Variables,  Up: Variables
  828. Scoping Rules for Variable Bindings
  829. ===================================
  830.    A given symbol `foo' may have several local variable bindings,
  831. established at different places in the Lisp program, as well as a global
  832. binding.  The most recently established binding takes precedence over
  833. the others.
  834.    Local bindings in Emacs Lisp have "indefinite scope" and "dynamic
  835. extent".  "Scope" refers to *where* textually in the source code the
  836. binding can be accessed.  Indefinite scope means that any part of the
  837. program can potentially access the variable binding.  "Extent" refers
  838. to *when*, as the program is executing, the binding exists.  Dynamic
  839. extent means that the binding lasts as long as the activation of the
  840. construct that established it.
  841.    The combination of dynamic extent and indefinite scope is called
  842. "dynamic scoping".  By contrast, most programming languages use
  843. "lexical scoping", in which references to a local variable must be
  844. located textually within the function or block that binds the variable.
  845.      Common Lisp note: Variables declared "special" in Common Lisp are
  846.      dynamically scoped, like variables in Emacs Lisp.
  847. * Menu:
  848. * Scope::          Scope means where in the program a value is visible.
  849.                      Comparison with other languages.
  850. * Extent::         Extent means how long in time a value exists.
  851. * Impl of Scope::  Two ways to implement dynamic scoping.
  852. * Using Scoping::  How to use dynamic scoping carefully and avoid problems.
  853. File: elisp,  Node: Scope,  Next: Extent,  Up: Variable Scoping
  854. Scope
  855. -----
  856.    Emacs Lisp uses "indefinite scope" for local variable bindings.
  857. This means that any function anywhere in the program text might access a
  858. given binding of a variable.  Consider the following function
  859. definitions:
  860.      (defun binder (x)   ; `x' is bound in `binder'.
  861.         (foo 5))         ; `foo' is some other function.
  862.      
  863.      (defun user ()      ; `x' is used in `user'.
  864.        (list x))
  865.    In a lexically scoped language, the binding of `x' in `binder' would
  866. never be accessible in `user', because `user' is not textually
  867. contained within the function `binder'.  However, in dynamically scoped
  868. Emacs Lisp, `user' may or may not refer to the binding of `x'
  869. established in `binder', depending on circumstances:
  870.    * If we call `user' directly without calling `binder' at all, then
  871.      whatever binding of `x' is found, it cannot come from `binder'.
  872.    * If we define `foo' as follows and call `binder', then the binding
  873.      made in `binder' will be seen in `user':
  874.           (defun foo (lose)
  875.             (user))
  876.    * If we define `foo' as follows and call `binder', then the binding
  877.      made in `binder' *will not* be seen in `user':
  878.           (defun foo (x)
  879.             (user))
  880.      Here, when `foo' is called by `binder', it binds `x'.  (The
  881.      binding in `foo' is said to "shadow" the one made in `binder'.)
  882.      Therefore, `user' will access the `x' bound by `foo' instead of
  883.      the one bound by `binder'.
  884. File: elisp,  Node: Extent,  Next: Impl of Scope,  Prev: Scope,  Up: Variable Scoping
  885. Extent
  886. ------
  887.    "Extent" refers to the time during program execution that a variable
  888. name is valid.  In Emacs Lisp, a variable is valid only while the form
  889. that bound it is executing.  This is called "dynamic extent".  "Local"
  890. or "automatic" variables in most languages, including C and Pascal,
  891. have dynamic extent.
  892.    One alternative to dynamic extent is "indefinite extent".  This
  893. means that a variable binding can live on past the exit from the form
  894. that made the binding.  Common Lisp and Scheme, for example, support
  895. this, but Emacs Lisp does not.
  896.    To illustrate this, the function below, `make-add', returns a
  897. function that purports to add N to its own argument M.  This would work
  898. in Common Lisp, but it does not work as intended in Emacs Lisp, because
  899. after the call to `make-add' exits, the variable `n' is no longer bound
  900. to the actual argument 2.
  901.      (defun make-add (n)
  902.          (function (lambda (m) (+ n m))))  ; Return a function.
  903.           => make-add
  904.      (fset 'add2 (make-add 2))  ; Define function `add2'
  905.                                 ;   with `(make-add 2)'.
  906.           => (lambda (m) (+ n m))
  907.      (add2 4)                   ; Try to add 2 to 4.
  908.      error--> Symbol's value as variable is void: n
  909.    Some Lisp dialects have "closures", objects that are like functions
  910. but record additional variable bindings.  Emacs Lisp does not have
  911. closures.
  912. File: elisp,  Node: Impl of Scope,  Next: Using Scoping,  Prev: Extent,  Up: Variable Scoping
  913. Implementation of Dynamic Scoping
  914. ---------------------------------
  915.    A simple sample implementation (which is not how Emacs Lisp actually
  916. works) may help you understand dynamic binding.  This technique is
  917. called "deep binding" and was used in early Lisp systems.
  918.    Suppose there is a stack of bindings: variable-value pairs.  At entry
  919. to a function or to a `let' form, we can push bindings on the stack for
  920. the arguments or local variables created there.  We can pop those
  921. bindings from the stack at exit from the binding construct.
  922.    We can find the value of a variable by searching the stack from top
  923. to bottom for a binding for that variable; the value from that binding
  924. is the value of the variable.  To set the variable, we search for the
  925. current binding, then store the new value into that binding.
  926.    As you can see, a function's bindings remain in effect as long as it
  927. continues execution, even during its calls to other functions.  That is
  928. why we say the extent of the binding is dynamic.  And any other function
  929. can refer to the bindings, if it uses the same variables while the
  930. bindings are in effect.  That is why we say the scope is indefinite.
  931.    The actual implementation of variable scoping in GNU Emacs Lisp uses
  932. a technique called "shallow binding".  Each variable has a standard
  933. place in which its current value is always found--the value cell of the
  934. symbol.
  935.    In shallow binding, setting the variable works by storing a value in
  936. the value cell.  Creating a new binding works by pushing the old value
  937. (belonging to a previous binding) on a stack, and storing the local
  938. value in the value cell.  Eliminating a binding works by popping the
  939. old value off the stack, into the value cell.
  940.    We use shallow binding because it has the same results as deep
  941. binding, but runs faster, since there is never a need to search for a
  942. binding.
  943. File: elisp,  Node: Using Scoping,  Prev: Impl of Scope,  Up: Variable Scoping
  944. Proper Use of Dynamic Scoping
  945. -----------------------------
  946.    Binding a variable in one function and using it in another is a
  947. powerful technique, but if used without restraint, it can make programs
  948. hard to understand.  There are two clean ways to use this technique:
  949.    * Use or bind the variable only in a few related functions, written
  950.      close together in one file.  Such a variable is used for
  951.      communication within one program.
  952.      You should write comments to inform other programmers that they
  953.      can see all uses of the variable before them, and to advise them
  954.      not to add uses elsewhere.
  955.    * Give the variable a well-defined, documented meaning, and make all
  956.      appropriate functions refer to it (but not bind it or set it)
  957.      wherever that meaning is relevant.  For example, the variable
  958.      `case-fold-search' is defined as "non-`nil' means ignore case when
  959.      searching"; various search and replace functions refer to it
  960.      directly or through their subroutines, but do not bind or set it.
  961.      Then you can bind the variable in other programs, knowing reliably
  962.      what the effect will be.
  963.    In either case, you should define the variable with `defvar'.  This
  964. helps other people understand your program by telling them to look for
  965. inter-function usage.  It also avoids a warning from the byte compiler.
  966. Choose the variable's name to avoid name conflicts--don't use short
  967. names like `x'.
  968.